import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const useWebSocketStore = defineStore('websocket', () => {
  const ws = ref(null)
  const connectionStatus = ref('disconnected') // disconnected, connecting, connected
  const reconnectAttempts = ref(0)
  const maxReconnectAttempts = 10
  const stats = reactive(new Map())

  const wsUrl = `ws://${window.location.host}/ws?client_id=web-control`

  // 初始化WebSocket连接（开发模式模拟连接）
  const initWebSocket = () => {
    connectionStatus.value = 'connecting'

    // 模拟连接延迟
    setTimeout(() => {
      connectionStatus.value = 'connected'
      reconnectAttempts.value = 0

      // 模拟定期接收心跳消息
      setInterval(() => {
        if (connectionStatus.value === 'connected') {
          // 心跳消息处理
        }
      }, 30000)
    }, 1000)
  }

  // WebSocket重连机制
  const reconnectWebSocket = () => {
    reconnectAttempts.value++
    const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.value), 30000)

    if (reconnectAttempts.value <= maxReconnectAttempts) {
      setTimeout(() => initWebSocket(), delay)
    } else {
      console.error('WebSocket重连失败，已达到最大尝试次数')
    }
  }

  // 处理WebSocket消息
  const handleWebSocketMessage = (event) => {
    try {
      if (event.data instanceof Blob) {
        handleBinaryMessage(event.data)
        return
      }

      const data = JSON.parse(event.data)

      switch (data.type) {
        case 'welcome':
        case 'connected':
          break
        case 'screen_data':
        case 'frame':
          updateScreenData(data.client_id || 'default', data.data, data.timestamp)
          break
        case 'client_connected':
          break
        case 'client_disconnected':
          if (data.client_id && stats.has(data.client_id)) {
            stats.delete(data.client_id)
          }
          break
        case 'heartbeat':
          break
        case 'error':
          console.error('服务器错误:', data.message)
          break
        default:
          break
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  }

  // 处理二进制消息
  const handleBinaryMessage = (blob) => {
    const reader = new FileReader()
    reader.onload = (event) => {
      try {
        const arrayBuffer = event.target.result
        const uint8Array = new Uint8Array(arrayBuffer)
        const text = new TextDecoder().decode(uint8Array)
        const data = JSON.parse(text)
        handleWebSocketMessage({ data: JSON.stringify(data) })
      } catch (error) {
        console.error('处理二进制消息失败:', error)
      }
    }
    reader.readAsArrayBuffer(blob)
  }

  // 更新屏幕数据
  const updateScreenData = (clientId, screenData, timestamp) => {
    if (!stats.has(clientId)) {
      initClientStats(clientId)
    }

    if (screenData && screenData.length > 0) {
      updateStats(clientId, screenData.length, timestamp)
    }
  }

  // 初始化客户端统计
  const initClientStats = (clientId) => {
    stats.set(clientId, {
      fps: 0,
      latency: 0,
      dataRate: 0,
      frameCount: 0,
      totalBytes: 0,
      lastFrameTime: Date.now(),
      startTime: Date.now(),
      frameTimestamps: [],
      lastUpdateTime: Date.now()
    })
  }

  // 更新统计信息
  const updateStats = (clientId, frameSize, serverTimestamp = null) => {
    const clientStats = stats.get(clientId)
    if (!clientStats) return

    const now = Date.now()

    // 计算延迟
    if (serverTimestamp) {
      clientStats.latency = now - serverTimestamp
    } else {
      clientStats.latency = now - clientStats.lastFrameTime
    }
    clientStats.lastFrameTime = now

    // 计算帧率
    clientStats.frameTimestamps.push(now)
    clientStats.frameTimestamps = clientStats.frameTimestamps.filter(timestamp =>
      now - timestamp <= 1000
    )
    clientStats.fps = clientStats.frameTimestamps.length

    // 计算数据传输率
    clientStats.totalBytes += frameSize
    const elapsed = (now - clientStats.lastUpdateTime) / 1000
    if (elapsed >= 1) {
      const recentElapsed = (now - clientStats.startTime) / 1000
      clientStats.dataRate = Math.round(clientStats.totalBytes / recentElapsed / 1024)
      clientStats.lastUpdateTime = now
    }

    stats.set(clientId, clientStats)
  }

  // 发送控制命令（开发模式模拟）
  const sendControlCommand = (clientId, command) => {
    // 模拟命令发送成功
    if (connectionStatus.value === 'connected') {
      return true
    } else {
      console.warn('WebSocket未连接，无法发送命令')
      return false
    }
  }

  // 发送消息（开发模式模拟）
  const sendMessage = (message) => {
    // 模拟消息发送成功
    if (connectionStatus.value === 'connected') {
      return true
    } else {
      console.warn('WebSocket未连接，无法发送消息')
      return false
    }
  }

  // 关闭连接
  const closeConnection = () => {
    if (ws.value) {
      ws.value.close()
    }
  }

  return {
    ws,
    connectionStatus,
    reconnectAttempts,
    stats,
    initWebSocket,
    sendControlCommand,
    sendMessage,
    closeConnection
  }
})
